<template>
  <BasicModal
    v-bind="$attrs"
    title="商品信息列表"
    width="1000px"
    @ok="handleSelect"
    @register="registerInnerModal"
    @cancel="handleCloseModal"
  >
    <Tabs v-model:activeKey="activeKey">
      <TabPane v-for="item in productTypeArray" :key="item.typeKey" :tab="item.typeName">
        <BasicTable @register="registerTable" ref="selectTable">
          <template #bodyCell="{ column, text }">
            <template v-if="column.key === 'mainImage'">
              <Image :width="60" :src="text" />
            </template>
          </template>
        </BasicTable>
      </TabPane>
    </Tabs>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, defineEmits } from 'vue';
  import { Tabs, TabPane, Image } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTable, useTable } from '@/components/Table';
  import { getBasicColumns } from './productinfo.data';
  import { productTypeList } from '@/api/product/type';
  import { ProductTypeVO } from './productType';
  import { productInfoList } from '@/api/product/manage';

  const selectShopId = ref('');
  const activeKey = ref('');
  const productTypeArray = ref<ProductTypeVO[]>([]);
  const selectTable = ref<InstanceType<typeof BasicTable> | undefined>();

  // 定义可触发的事件
  const emit = defineEmits(['handleSubmit', 'handleClose']);

  onMounted(async () => {
    try {
      productTypeArray.value = await productTypeList();
      const productTypeKeyFirst = productTypeArray.value[0].typeKey;
      activeKey.value = productTypeKeyFirst;
    } catch (error) {
      console.error('获取产品类型列表时发生错误:', error);
    }
  });

  const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
    async (data: { shopId: string }) => {
      modalLoading(true);
      const { shopId } = data;
      selectShopId.value = shopId;
      modalLoading(false);
    },
  );

  const [registerTable, { getSelectRows }] = useTable({
    canResize: true,
    api: productInfoList,
    searchInfo: {
      productType: activeKey,
      shopId: selectShopId,
    },
    columns: getBasicColumns(),
    defSort: {
      field: 'name',
      order: 'ascend',
    },
    rowKey: 'id',
    showTableSetting: true,
    rowSelection: {
      type: 'checkbox',
    },
    showSelectionBar: true, // 显示多选状态栏
  });

  async function handleCloseModal() {
    emit('handleClose');
    closeModal();
  }

  async function handleSelect() {
    try {
      modalLoading(true);
      emit('handleSubmit', getSelectRows());
      closeModal();
    } catch (e) {
    } finally {
      modalLoading(false);
    }
  }
</script>
